#include "ProcessMessage.h"
#include "Protocol/Protocol.h"
#include "Protocol/ProtocolHelper.h"
#include <QDataStream>
#include <QDebug>
#include "MainWindow.h"

ProcessMessage::ProcessMessage(QByteArray msg, ClientThread* thread, ClientManager* manager) :
	_data(msg),
	_clientThread(thread),
	_clientManager(manager)
{
}

QByteArray ProcessMessage::process()
{
	MainWindow::addLogMsg(QString("Input[%1]: %2").arg(_data.size()) + _data.toHex(), Log::ILogManager::DEBUG);
	QByteArray ret;
	if(_data.size() == 0) return ret;

	QDataStream readStream(&_data, QIODevice::ReadOnly);
	QDataStream writeStream(&ret, QIODevice::WriteOnly);

	quint8 messageType;
	readStream >> messageType;

	switch(messageType){
		case VERSION_REQUEST:
			writeStream << (quint8) VERSION_RESPONSE;
			writeStream << (quint16) PROTOCOL_VERSION;
			break;
		case SET_USER_NAME:{
			QString name = Protocol::Helper::fromStringStream(readStream);
			MainWindow::addLogMsg("Set user name: " + name);
			writeStream << (quint8) EMPTY_RESPONSE;
			_clientManager->updateName(_clientThread, name);
			break;}
		case USER_LIST_REQUEST:
			writeStream << (quint8) USER_LIST_RESPONSE;
			writeStream << (quint16) _clientManager->users().count();
			foreach(ClientInfo info, _clientManager->users()){
				writeStream << (quint32) info.user.id();
				Protocol::Helper::enumToDataStream(writeStream, info.user.state());
				Protocol::Helper::stringToDataStream(writeStream, info.user.name());
				MainWindow::addLogMsg(QString("SendUserData: %1[%2]-%3").arg(info.user.id()).arg(info.user.name()).arg(info.user.state()));
			}
			break;
	}

	return ret;
}
